package com.kedacom.demo.hmac;

import java.security.GeneralSecurityException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HMACUtils {

	public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	public static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
	public static final String HMAC_HEAD_NAME = "hmac";

	private static final Logger logger = LoggerFactory.getLogger(HMACUtils.class);

	public static String calculateHMAC(String secret, String data) {
		try {
			SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA1_ALGORITHM);
			Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(data.getBytes());
			return Base64.encodeBase64String(rawHmac);
		} catch (GeneralSecurityException e) {
			logger.warn("Unexpected error while creating hash: " + e.getMessage(), e);
			throw new IllegalArgumentException();
		}
	}

	public static String populateHMACContent(String httpMethod, String contentMd5, String contentType, String datetime,
			String requestURI) {
		// sso token,
		return httpMethod + "\n" + contentMd5 + "\n" + contentType + "\n" + datetime + "\n" + requestURI;
	}

}
